//
//  RPersonViewController.m
//  Riji
//
//  Created by  on 2022/8/17.
//

#import "RPersonViewController.h"
#import "RMineCell.h"

@interface RPersonViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong) NSArray *data;
@property (nonatomic, strong) NSArray *cellTypes;
@property (nonatomic, strong) NSMutableArray *content;

@end

@implementation RPersonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
- (void)initUI
{
    self.title = LS(@"个人信息");
    self.data = @[@"头像",@"昵称",@"用户名",@"性别"];
    self.content = [NSMutableArray arrayWithArray:@[@"",APP.user.username,APP.user.ID,APP.user.gender]];
    self.cellTypes = @[@(2),@(5),@(5),@(4)];
    [self.tableView registerNib:[RMineCell nib] forCellReuseIdentifier:[RMineCell ID]];
    [self.tableView reloadData];
}
- (void)http:(NSString *)api para:(NSDictionary*)dict{
    WS(self)
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@?",api];
    for (NSString *key in [dict allKeys]) {
        [url appendFormat:@"%@=%@&",key,dict[key]];
    }
    [CCHttp get:[url substringToIndex:url.length-1] para:nil header:nil success:^(id  _Nonnull response) {
        if ([[response valueForKey:@"status"] intValue] != 0) {
            return [RLHud msg:LS(@"错误")];
        }
        if ([api isEqualToString:api_updateName]) {
            APP.user.username = [dict valueForKey:@"username"];
        }else if ([api isEqualToString:api_updateAvatat]){
            APP.user.headImg = [dict valueForKey:@"url"];
        }
        [APP.user bg_saveOrUpdate];
        [[NSNotificationCenter defaultCenter] postNotificationName:notifyNoteUpdate object:nil];
        [weakself initUI];
    } fail:^(NSError * _Nonnull error) {}];
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    UIImage *img = [info valueForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(img, 0.5);
    WS(self)
    [CCHttp upload:api_upload para:nil data:imageData progress:^(NSURLSession * _Nonnull session, NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull response) {
        int code = [[response valueForKey:@"code"] intValue];
        NSString *str = code == 0 ? LS(@"上传成功"):LS(@"上传失败");
        [RLHud startHud:str stopTime:1 handle:^{
            if (code == 0) {
                [weakself http:api_updateAvatat para:@{@"url":response[@"data"]}];
            }
        }];
    } fail:^(NSError * _Nonnull error) {}];
    [picker dismissViewControllerAnimated:YES completion:^{
        [RLHud startHud:LS(@"上传图片中...")];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RMineCell *cell = [tableView dequeueReusableCellWithIdentifier:[RMineCell ID]];
    NSString *str = self.data[indexPath.row];
    NSString *con = self.content[indexPath.row];
    cell.type = (RMineCellType)[self.cellTypes[indexPath.row] intValue];
    cell.name.text = LS(str);
    if (indexPath.row == 0) {
        [UIImage imageWithURL:APP.user.headImg block:^(UIImage * _Nonnull image) {
            cell.infoIMG.image = image;
        }];
    }else{
        cell.info.text = LS(con);
    }
    return  cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return  nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(self)
    [tableView endEditing:YES];
    NSString * str = self.data[indexPath.row];
    if ([str isEqualToString:@"头像"]) {
        WS(self)
        [weakself sheet:nil msg:nil sheet:@[@"相机",@"相簿"] sheetBlock:^(int index, NSString *sheetTitle) {
            UIImagePickerController *vc = [[UIImagePickerController alloc] init];
            vc.delegate = self;
            vc.allowsEditing = YES;
            vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
            vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [weakself presentViewController:vc animated:YES completion:nil];
        }];
    }else if([str isEqualToString:@"昵称"]){
        RPopAlertViewController *vc = [RPopAlertViewController new];
        vc.input.hidden = NO;
        [vc.enterBtn setTitleColor:[UIColor colorWithHexString:@"#2F88EE"] forState:UIControlStateNormal];
        [vc.cancelBtn setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
        vc.enterBlock = ^(NSString * _Nonnull nickname) {
          NSString * str =[nickname stringByReplacingOccurrencesOfString:@" " withString:@""];
            if ([str length] <= 0) {
                return [RLHud msg:LS(@"昵称不能为空")];
            }else if ([str isNumberOrAlphabet] == NO){
                return [RLHud msg:LS(@"昵称只能包含数字和字母")];
            }
            [self http:api_updateName para:@{@"username":str}];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if([str isEqualToString:@"用户名"]){
    }else if ([str isEqualToString:@"性别"]){
        [weakself sheet:nil msg:nil sheet:@[@"男",@"女"] sheetBlock:^(int index, NSString *sheetTitle) {
            APP.user.gender = sheetTitle;
            [APP.user bg_saveOrUpdate];
            [weakself initUI];
        }];
    }
}


@end
